package com.donn.securitycontrolplatform.positioninformation.service;

import com.donn.securitycontrolplatform.mqtt.MqttReceiveHandle;
import com.donn.securitycontrolplatform.positioninformation.entity.RpmLocationDTO;
import com.donn.securitycontrolplatform.positioninformation.entity.TPositionInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MqttService extends MqttReceiveHandle {

    @Autowired
        private ITPositionInfoService service;

    @Override
    public void handle(String topic, Message<?> message) {
        if (topic.equals("rpm_pa/rtlocation")) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                RpmLocationDTO locationDTO = objectMapper.readValue(message.getPayload().toString(), RpmLocationDTO.class);
                if (locationDTO != null) {
                    TPositionInfo positionInfo = new TPositionInfo();
                    BeanUtils.copyProperties(locationDTO, positionInfo);
                    positionInfo.setTagId(locationDTO.getTagid());
                    positionInfo.setTs(System.currentTimeMillis());
                    service.save(positionInfo);
                }
            } catch (Exception e) {
                log.error("HANDLE ERROR ", e);
            }

        }
    }
}
